import request from '@/utils/request'
import { Message } from 'element-ui'

// 获取数据列表
export function fetchList(query) {
  return request({
    url: '/coupon/record/list',
    method: 'post',
    data: query
  })
}

// 新增
export function add(item) {
  return request({
    url: '/coupon/record/add',
    method: 'post',
    data: item
  })
}

// 新增
export function sendCouponByPhone(item) {
  return request({
    url: '/coupon/record/sendCouponByPhone',
    method: 'post',
    data: item
  })
}

// 修改
export function update(item) {
  return request({
    url: '/coupon/record/update',
    method: 'post',
    data: item
  })
}

// 删除
export function del(item) {
  return request({
    url: '/coupon/record/delete',
    method: 'post',
    data: { id: item }
  })
}

// 获取数据列表
export function findByObject(query) {
  return request({
    url: '/coupon/record/findByObject',
    method: 'post',
    data: query
  })
}

// 导出excel
export function exportExcel(query) {
  const fileName = '优惠券记录信息导出.xlsx'
  request({ url: '/coupon/record/export', method: 'download', data: query }).then(res => {
    console.log(res)
    if (res.type === 'application/json') {
      const reader = new FileReader()
      reader.onload = function() {
        const { msg } = JSON.parse(reader.result)
        console.log(msg)
        Message({
          message: msg,
          type: 'error',
          duration: 3 * 1000
        })
      }
      reader.readAsText(res)
    } else {
      // 这里需要根据不同的文件格式写不同的参数
      const blob = new Blob([res], {
        type: 'application/xlsx'
      })
      const eLink = document.createElement('a')
      eLink.download = fileName
      eLink.style.display = 'none'
      eLink.href = URL.createObjectURL(blob)
      document.body.appendChild(eLink)
      eLink.click()
      URL.revokeObjectURL(eLink.href)
      document.body.removeChild(eLink)
    }
  })
}
